<?php
/**
 * SetupDb.php
 *
 * @category    Madoqua
 * @package     Module
 * @subpackage  Install
 */

/**
 * Install_SetupDb
 *
 * @category    Madoqua
 * @package     Module
 * @subpackage  Install
 */
abstract class Install_SetupDb
{
    /**
     * database connection
     *
     * @var Zend_Db_Adapter_Abstract
     */
    protected $_connection;

    /**
     * tables that have to exist for a succesfull install
     *
     * @var array
     */
    protected $_tables = array(
    'category',
    'comment', 
    'page', 
    'post', 
    'post_category', 
    'user' 
    );

    /**
     * constructor
     */
    public function __construct()
    {
        $this->_connection = Madoqua_Application::getDatabase(true);
        //retrieve db connection
    }

    /**
     * check whether the install has a chance of succeeding
     *
     * @return bool
     */
    abstract public function canInstall();

    /**
     * perform the installation
     *
     * @return void
     */
    abstract public function install();

    /**
     * check whether installation was succesful
     *
     * @return bool
     */
    public function isInstalled()
    {
        $installedTables = $this->_connection->listTables();
        //the tables that have been installed
        
        $prefix = Madoqua_Application::getConfiguration()->database->prefix;
        //table prefix
        
        foreach($this->_tables as $requiredTable) {
            $requiredTable = $prefix . $requiredTable;
            //add prefix
            
            if (!in_array($requiredTable, $installedTables)) {
                //uh ohw... one is missing! :(
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * get the mysql-sql
     *
     * @return string
     */
    protected function getSql($type)
    {
        $contents = file_get_contents(dirname(__FILE__) . '/sql/' . $type . '.sql');
        //contents of relevant sql file
        
        $prefix = Madoqua_Application::getConfiguration()->database->prefix;
        //table prefix
        
        $contents = str_replace('{prefix}', $prefix, $contents);
        //add prefix to table names
        
        $splode = explode(';', $contents);
        //oh noes... it 'sploded!
        
        $result = array();
        //return array
        
        foreach($splode as $key => $query) {
            $query = trim($query);
            if (!empty($query)) {
                $result[] = $query;
            }
        }
        //parse file (remove empty queries)

        return $result;
    }    
}